package com.xiaoma.thread.wait;

import java.lang.Thread.State;
import org.junit.Test;

public class TestReenterBlocked {

  @Test
  public void testReenterBlocked() throws Exception {
    class Account {
      int amount = 100; // 账户初始100元
      public synchronized void deposit(int cash) { // 存钱
        amount += cash;
        notify();
        try {
          Thread.sleep(30000); // 通知后却暂时不退出
        } catch (InterruptedException e) {
          throw new RuntimeException(e);
        }
      }
      public synchronized void withdraw(int cash) { // 取钱
        while (cash > amount) {
          try {
            wait();
          } catch (InterruptedException e) {
            throw new RuntimeException(e);
          }
        }
        amount -= cash;
      }
    }

    Account account = new Account();

    Thread withdrawThread = new Thread(new Runnable() {
      public void run() {
        account.withdraw(200);
      }
    }, "取钱线程");
    withdrawThread.start();

    Thread.sleep(100); // 确保取钱线程已经得到执行

    System.out.println(withdrawThread.getState().equals(State.WAITING));

    Thread depositThread = new Thread(new Runnable() {
      public void run() {
        account.deposit(100);
      }
    }, "存钱线程");
    Thread.sleep(10000); // 让取钱线程等待一段时间
    depositThread.start();

    Thread.sleep(300); // 确保取钱线程已经被存钱线程所通知到

    System.out.println(withdrawThread.getState().equals(State.BLOCKED));
  }

}
